<?php
/**
 * Created by PhpStorm.
 * User: jwb
 * Date: 2020/5/12
 * Time: 16:37
 */

namespace App\Repositories;

use App\PatentFee;
use App\Repositories\Eloquent\Repository;
use Carbon\Carbon;
use Encore\Admin\Facades\Admin;
use Illuminate\Database\Eloquent\Builder;

class PatentFeeRepository extends Repository
{
    function model()
    {
        return PatentFee::class;
    }

    public function siteGrid($role)
    {
        $user = Admin::user();
        $grid = $this->grid();
        $grid->model()->whereHas('patent', function (Builder $query) use ($user, $role) {
            return $query->whereIn('patent_type_id', [1, 2, 3])
                ->when(!$role, function (Builder $query) use ($user) {
                    $query->where('user_id', $user['id']);
                });
        })->orderBy('last_time')->orderBy('patent_sn');
        return $grid;
    }

    public function totalByLastDate($user, $month, $is_user = true)
    {
        return $this->model->where('state', 0)
            ->whereHas('patent', function ($query) use ($user, $is_user) {
                $where = $is_user ? [['user_id', $user->id]] : [];
                $query->where($where);
            })->when($month, function (Builder $query) use ($month) {
                $query->whereDate('last_time', '<=', Carbon::now()->addMonths($month)->toDateString());
            }, function (Builder $query) {
                $query->whereDate('last_time', '<=', Carbon::now()->toDateString());
            })
            ->sum('amount');
    }

}
